package wpspider.client.dao.http;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import wpspider.client.model.Page;

/**
 * XMLParser class.
 *
 */
public final class XMLParser {

    /**
     * Constructor. (private)
     */
    private XMLParser() {
    }

    /**
     * Parses Page XML.
     * @param inputStream
     * @return List of PageInfo.
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws IOException
     * @throws TransformerException
     * @throws XPathExpressionException
     */
    public static List<Page> parsePageXML(InputStream inputStream) throws ParserConfigurationException, SAXException, IOException, TransformerException, XPathExpressionException {
        List<Page> pageInfos = new ArrayList<Page>();
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = documentBuilder.parse(inputStream);
        XPath xpath = XPathFactory.newInstance().newXPath();
        NodeList pageElements = (NodeList) xpath.evaluate("/wpspider/pages/page", document, XPathConstants.NODESET);
        if (pageElements != null) {
            int pageElementsSize = pageElements.getLength();
            for (int i = 0; i < pageElementsSize; i++) {
                Node pageElement = pageElements.item(i);
                String name = (String) xpath.evaluate("name/text()", pageElement);
                String size = (String) xpath.evaluate("size/text()", pageElement);
                List<String> words = new ArrayList<String>();
                NodeList wordElements = (NodeList) xpath.evaluate("words/word", pageElement, XPathConstants.NODESET);
                for (int j = 0; j < wordElements.getLength(); j++) {
                    Node wordElement = wordElements.item(j);
                    String word = (String) xpath.evaluate("text()", wordElement);
                    words.add(word);
                }
                Page page = new Page(name, words);
                pageInfos.add(page);
            }
        }
        return pageInfos;
    }
}
